package
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.display.DisplayObject;
	import flash.geom.Vector3D;

	[SWF(width="600", height="600", frameRate="24", backgroundColor="0xFFFFFF")]
	public class pungCha extends Sprite
	{

		private var sp:Sprite = new Sprite();
		private var itemArr:Array = new Array();
		private var itemCnt:int = 20;
		private var boxWidth:int = 50;
		private var boxHeight:int = 150;

		public function pungCha()
		{
			// constructor code
			displayMain();
			createWheels();
			stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
		}

		private function displayMain():void
		{
			sp.x = stage.stageWidth / 2;
			sp.y = stage.stageHeight / 2;
			sp.z = 0;
			this.addChild(sp);
		}

		private function createWheels():void
		{
			for (var i:int = 0; i < itemCnt; i++)
			{
				var angle:Number = Math.PI * 2 / itemCnt * i;
				var item:Sprite = new Sprite();
				item.graphics.beginFill(Math.random() * 0x1000000);
				item.graphics.drawRect(-boxWidth, -boxHeight, 2 * boxWidth, 2 * boxHeight);

				item.y = Math.cos(angle) * boxHeight;
				item.z = Math.sin(angle) * boxHeight;

				item.rotationX = 360 / itemCnt * i;
				itemArr.push(item);
				sp.addChild(item);
			}
			sp.rotationY = 100;
			sortItems();
		}

		private function enterFrameHandler(event:Event):void
		{
			sp.transform.matrix3D.prependRotation(-(stage.stageHeight / 2 - mouseY)

				* 0.01, Vector3D.X_AXIS);
			//sp.rotationX += -(stage.stageHeight / 2 - mouseY ) * .01;
			sortItems();
		}

		private function sortItems():void
		{
			itemArr.sort(depthSort);

			for (var i:int = 0; i < itemArr.length; i++)
			{
				sp.addChildAt(itemArr[i] as Sprite, i);
			}
		}

		private function depthSort(objA:DisplayObject, objB:DisplayObject):int
		{
			var posA:Vector3D = objA.transform.matrix3D.position;
			posA = sp.transform.matrix3D.deltaTransformVector(posA);
			var posB:Vector3D = objB.transform.matrix3D.position;
			posB = sp.transform.matrix3D.deltaTransformVector(posB);
			return posB.z - posA.z;
		}

	}

}

